package com.ly.proxy615.dynamicsProxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

public class CglibTest {


    /**
     * 真实方法
     */
    public void run(String ip){
        System.out.println("方法正在运行");
    }

    /**
     * 代理类
     */
    static class NoProxy implements MethodInterceptor{

        //通过Enhancer创建代理对象
        private Enhancer enhancer = new Enhancer();
        //通过class对象创建对象
        public Object getProxy(){
            //设置所需类
            enhancer.setSuperclass(CglibTest.class);
            enhancer.setCallback(this);
            return enhancer.create();//通过字节码技术创建代理对象
        }
        //代理方法
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("开始参数为"+ Arrays.toString(objects));
            methodProxy.invokeSuper(o,objects);
            System.out.println("结束");
            return null;
        }


    }

    public static void main(String[] args) {
        NoProxy noProxy = new NoProxy();
        CglibTest proxy = (CglibTest) noProxy.getProxy();
        proxy.run("127");
    }
}
